

package org.koyabr.webx.demo.danmaku.web.post.module.action;

import com.alibaba.citrus.service.form.Group;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.turbine.dataresolver.FormGroup;

import static org.koyabr.webx.demo.danmaku.web.common.DanmakuConstant.*;
import org.koyabr.webx.demo.danmaku.biz.DuplicatedPostException;
import org.koyabr.webx.demo.danmaku.biz.PostManager;
import org.koyabr.webx.demo.danmaku.biz.UserManager;
import org.koyabr.webx.demo.danmaku.dal.dataobjs.Post;
import org.koyabr.webx.demo.danmaku.dal.dataobjs.User;
import org.koyabr.webx.demo.danmaku.web.common.DanmakuUser;
import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;

public class PostAction {
    @Autowired
    private PostManager postManager;
    
    @Autowired
    private UserManager userManager;

    public void doPublish(@FormGroup("post") Group group,  Navigator nav)
            throws Exception {
    	
    	User user = userManager.getUser(DanmakuUser.getCurrentUser().getUsername());
    	if(user == null){
    		nav.redirectTo(DANMAKU_LOGIN_LINK);
    	}
        Post post = new Post(user);
        FileItem picture = group.getField("pictureUpload").getFileItem();

        group.setProperties(post);

        try {
            postManager.addPost(post, picture);
            nav.redirectTo(DANMAKU_POST_MANAGE_LINK);
        } catch (DuplicatedPostException e) {
            group.getField("title").setMessage("duplicatedPostTitle");
        }
    }
}
